import utils.utils as utils
from querier.esquerier import ElasticSearchQuerier


class WetaoKOLInfoQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(WetaoKOLInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args.get('biz_code')
        ids_ = args.get('biz_codes')
        if id_ is None and ids_ is None:
            raise ValueError('message: "biz_code" or "biz_codes"(list of "biz_code") is needed')

        if id_ is not None:
            try:
                res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
            except Exception as e:
                print(str(e))
                res = {"Error": "No such biz_code found: " + str(ids_)}
            return self._build_result(res, None)
        else:
            out = []
            for i in ids_:
                try:
                    res = self.es.get(index=self.index, doc_type=self.doc_type, id=i)
                    res = self._build_result(res, None)
                except Exception as e:
                    print(str(e))
                    res = {"Error": "No such biz_code found: " + str(i)}
                out.append(res)
            return {"infos": out}

    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        if es_result.get('found'):
            source_ = es_result['_source']
            source_ = dict(source_)
            biz_info = source_['biz_info']

            kol_avatar_url = source_['avatar']
            if not kol_avatar_url:
                kol_avatar_url = ''
            if not kol_avatar_url.startswith('http'):
                kol_avatar_url = "http:" + kol_avatar_url
            kol_influence_score = source_['score']
            biz_code = source_['biz_code']
            biz_name = source_['biz_name']
            biz_tag = source_.get('biz_tag')
            if biz_tag:
                if len(biz_tag) > 10:
                    biz_tag = ''
                else:
                    biz_tag = biz_tag
            else:
                biz_tag = ''

            return {
                'biz_name': biz_name,
                'biz_code': biz_code,
                'biz_info': biz_info,
                'keywords': source_.get('keywords', [])[0:10],
                'head_img': kol_avatar_url,
                'score': kol_influence_score,
                'sum_read_num': source_.get('sum_read_num', 0),
                'avg_read_num': source_.get('avg_read_num', 0),
                'max_read_num': source_.get('max_read_num', 0),
                'min_read_num': source_.get('min_read_num', 0),
                'sum_like_num': source_.get('sum_like_num', 0),
                'avg_like_num': source_.get('avg_like_num', 0),
                'max_like_num': source_.get('max_like_num', 0),
                'min_like_num': source_.get('min_like_num', 0),
                'like_read_ratio': 1.0 if source_.get('like_read_ratio', 0.0) > 1 else source_.get('like_read_ratio',
                                                                                                   0),
                'user_type': source_.get('user_type', 0),
                # 'biz_link': biz_link,
                'media_name': source_.get('media_name'),
                'biz_tag': biz_tag,
                'category_taobao': source_.get('category_taobao', ''),
                'shop_id': source_.get('shop_id', ''),
                'biz_link': 'http://market.m.taobao.com/apps/abs/8/37/index?accountId=' + biz_code

            }

